package com.dianping.index;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class SearchIndex
{
    private static final String INDEX_DIR="E:\\index";
    public static void main(String[] args){
        
        try
        {
            InputStreamReader isr = new InputStreamReader(System.in, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            System.out.println("please enter the key words:");
            
            try
            {   
                String keyWords=br.readLine();
                while(keyWords!=null){
                    sb.append(keyWords);
                    System.out.println("please enter the key words:");
                    keyWords = br.readLine();
                    if(keyWords.trim().equals("")){
                        break;
                    }
                }
               // System.out.println(sb.toString());
                QueryParser qp = new QueryParser(Version.LUCENE_35, "contents", new StandardAnalyzer(Version.LUCENE_35));
                IndexSearcher indexSearcher = new IndexSearcher(FSDirectory.open(new File(INDEX_DIR)));
                Query query = qp.parse(sb.toString());
                TopDocs topDocs = indexSearcher.search(query, 10);
                System.out.println("找到了"+topDocs.totalHits+"个");
                for(int i=0;i<topDocs.scoreDocs.length;i++){
                    ScoreDoc scoreDoc = topDocs.scoreDocs[i];
                    Document doc = indexSearcher.doc(scoreDoc.doc);
                    System.out.println(doc.get("filename"));
                }
                indexSearcher.close();
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        catch (UnsupportedEncodingException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
